<?php

use App\Models\Application\Muticolumn;
use App\Models\Application\Pagetpl;
use App\Models\Application\Paneltpl;
use App\Models\Asset\Poster;
use App\Models\Common\EntityData\Channel\Sp;
use App\Models\Entity\Asset\Video\Vasseti;
use App\Models\Entity\Column\Collist;
use App\Models\Entity\Column\ColumnType;
use App\Models\ModelManage\JsonField;
use App\Models\ModelManage\Table;
use App\Models\ModelManage\TableField;
use App\Models\Page\PageStyle;
use App\Models\Recommend\ApppageRectpl;
use App\Models\Recommend\ApppageRectplArea;
use App\Models\Recommend\ApppageRectplData;
use App\Models\Recommend\Reclist0;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use \App\Classes\DataRelease\ApppageRectplRelease;
use \App\Classes\DataRelease\CollistDataRelease;
use \App\Classes\DataRelease\CollistRelease;
use \App\Classes\DataRelease\DataRelease;
use \App\Classes\DataRelease\MetaDataRelease;
use \App\Classes\DataRelease\MuticolumnRelease;
use \App\Classes\DataRelease\VassetiRelease;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
 */

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

/**
 * 媒资(电视剧总集和电影)注入
 */
// 媒资(电视剧总集和电影)注入
Route::get('/entity/asset/video/vassetis/injection/view', ['as' => 'entity.asset.video.vassetis.injection', 'uses' => 'Entity\Asset\Video\VassetiController@injection']);
// 媒资(电视剧总集和电影)注入的进度
Route::get('/entity/asset/video/vassetis/injection_progress/view', [
    'as'   => 'entity.asset.video.vassetis.injection_progress',
    'uses' => 'Entity\Asset\Video\VassetiController@injectionProgress',
]);
// 单个或多个媒资(电视剧总集和电影)注入
Route::get('/entity/asset/video/vassetis/inject_one_or_more/view', [
    'as'   => 'entity.asset.video.vassetis.inject_one_or_more',
    'uses' => 'Entity\Asset\Video\VassetiController@injectOneOrMore',
]);

/**
 * 媒资(分集)注入
 */
// 媒资(分集)注入
Route::get('/entity/asset/video/vserialis/injection/view', ['as' => 'entity.asset.video.vserialis.injection', 'uses' => 'Entity\Asset\Video\VserialiController@injection']);
// 媒资(分集)注入的进度
Route::get('/entity/asset/video/vserialis/injection_progress/view', [
    'as'   => 'entity.asset.video.vserialis.injection_progress',
    'uses' => 'Entity\Asset\Video\VserialiController@injectionProgress',
]);
// 单个或多个媒资(分集)注入
Route::get('/entity/asset/video/vserialis/inject_one_or_more/view', [
    'as'   => 'entity.asset.video.vserialis.inject_one_or_more',
    'uses' => 'Entity\Asset\Video\VserialiController@injectOneOrMore',
]);

/**
 * 媒资(直播)注入
 */
// 媒资(直播)注入
Route::get('/entity/asset/vlive/vchans/injection/view', ['as' => 'entity.asset.vlive.vchans.injection', 'uses' => 'Entity\Asset\Vlive\VchanController@injection']);
// 媒资(直播)注入的进度
Route::get('/entity/asset/vlive/vchans/injection_progress/view', [
    'as'   => 'entity.asset.vlive.vchans.injection_progress',
    'uses' => 'Entity\Asset\Vlive\VchanController@injectionProgress',
]);
// 单个或多个媒资(直播)注入
Route::get('/entity/asset/vlive/vchans/inject_one_or_more/view', [
    'as'   => 'entity.asset.vlive.vchans.inject_one_or_more',
    'uses' => 'Entity\Asset\Vlive\VchanController@injectOneOrMore',
]);

/**
 * 【分集选剧集的时候】新建分集添加剧集
 */
Route::get('entity/asset/video/vserialis/vserialis/vassetis', ['as' => 'entity.asset.video.vserialis.vassetis', 'uses' => 'Entity\Asset\Video\VserialiController@selectVasseti']);

/**
 * 点播媒资归类分类联动
 */
Route::get('common/tag_data/video/vcattags/vcattags/vcattag_or_empty', ['as' => 'common.cat_data.video.vcats.vcattag_or_empty', 'uses' => 'Common\TagData\Video\VcattagController@vcattagOrEmpty']);

/**
 * 直播媒资归类分类联动
 */
Route::get('common/cat_data/video/vccattags/vccattags/vccattag_or_empty', ['as' => 'common.cat_data.video.vccats.vccattag_or_empty', 'uses' => 'Common\TagData\Video\VccattagController@vccattagOrEmpty']);

/**
 * 数据发布接口
 */
Route::get('/asset/datas/release', function (Request $request) {
    // 要发布的文件目录
    $dataRelease = new \App\Classes\DataRelease\DataRelease();

    $dataRelease->releaseVassetiDatas();
    $dataRelease->releaseVseriaiDatas();
    $dataRelease->releaseColumnDatas();
    $dataRelease->releaseSubcolumnDatas();
    $dataRelease->releaseColumnRecommendDatas();
    $dataRelease->releaseSubcolumnRecommendDatas();
    $dataRelease->releaseCollistRecommendDatas();

});
/**
 * 获取栏目列表数据
 */
Route::get('/ott/{spid}/{termid}/collists/{collist_name}', function ($spid, $termid, $collistName, Request $request) {
    // 校验SP
    $sp = SP::where(['id' => $spid])->first();
    if (empty($sp)) {
        return response()->json(['status' => '404', 'data' => '无此服务商']);
    }
    $collistName = strtoupper($collistName);
    // 校验栏目列表
    $collist = Collist::where(['name' => $collistName, 'sp_id' => $spid])->first();
    if (empty($collist)) {
        return response()->json(['status' => '404', 'data' => '无此栏目列表']);
    }
    $collistId = $collist->id;
    // 获取请求参数
    $whereData = $request->all();
    // 实例化数据发布接口
    $collistDataRelease = new CollistDataRelease();
    // 调用栏目列表发布接口
    $data = $collistDataRelease->makeCollistDatas($spid, $termid, $collistId, $whereData);

    return response()->json(['status' => '200', 'data' => $data['data'], 'page' => $data['page']]);
});

/**
 * 获取推荐位数据
 */
Route::get('/ott/{spid}/{termid}/paneltpl/{pagetpl_name}/{apppageRectpl_name}', function ($spid, $termid, $pagetplName, $apppageRectplName, Request $request) {
    // 校验SP
    $sp = SP::where(['id' => $spid])->first();
    if (empty($sp)) {
        return response()->json(['status' => '404', 'data' => '无此服务商']);
    }
    // 页面模板名称
    $pagetplName = strtoupper($pagetplName);
    // 页面模板
    $pagetpl = Pagetpl::where(['name' => $pagetplName])->first();
    if (empty($pagetpl)) {
        return response()->json(['status' => '404', 'data' => '无此pageTpl模板']);
    }
    // // panelTpl模板
    // $paneltpl = Paneltpl::where(['name' => $paneltplName])->first();
    // if (empty($paneltpl)) {
    //     return response()->json(['status' => '404', 'data' => '无此panelTpl模板']);
    // }
    // $paneltplId = $paneltpl->id;
    // 获取请求参数
    $whereData = $request->all();
    $pagetplId = $pagetpl->id;
    // 根据栏目模板ID,页面Id获取推荐位
    // $apppageRectpl = ApppageRectpl::where(['pagetpl_id' => $pagetplId, 'paneltpl_id' => $paneltplId])->first();
    $apppageRectpl = ApppageRectpl::where(['name' => $apppageRectplName])->first();
    if (empty($apppageRectpl)) {
        return response()->json(['status' => '404', 'data' => '无此推荐位']);
    }
    $apppageRectplId = $apppageRectpl->id;
    // 实例化数据发布接口
    $dataRelease = new ApppageRectplRelease();
    // 调用栏目列表发布接口
    $data = $dataRelease->makePageRectplDatas($spid, $termid, $apppageRectplId, $whereData);

    return response()->json(['status' => '200', 'type' => $data['type'], 'data' => $data['data']]);
});

/**
 * 使用指定頁面模板加载栏目数据
 */
Route::get('/ott/{spid}/{termid}/pagetpl/{pagetpl_name}/column/{column_name}', function ($spid, $termid, $pagetplName, $columnName, Request $request) {

    // 校验SP
    $sp = SP::where(['id' => $spid])->first();
    if (empty($sp)) {
        return response()->json(['status' => '404', 'data' => '无此服务商']);
    }
    // 页面模板名称
    $pagetplName = strtoupper($pagetplName);
    // 页面模板
    $pagetpl = Pagetpl::where(['name' => $pagetplName])->first();
    if (empty($pagetpl)) {
        return response()->json(['status' => '404', 'data' => '无此pageTpl模板']);
    }
    // panelTpl模板paneltplName
    $muticolumn = Muticolumn::where(['name' => $columnName])->first();
    if (empty($muticolumn)) {
        return response()->json(['status' => '404', 'data' => '无此栏目']);
    }
    // 获取请求参数
    $whereData    = $request->all();
    $pagetplId    = $pagetpl->id;
    $muticolumnId = $muticolumn->id;
    // 实例化数据发布接口
    $dataRelease = new MuticolumnRelease();
    // 调用栏目列表发布接口
    $data = $dataRelease->makePagetplColumnData($spid, $termid, $pagetplId, $muticolumnId, $whereData);

    return response()->json(['status' => '200', 'data' => $data]);
});
/**
 * 使用指定頁面模板加载栏目列表数据
 */
Route::get('/ott/{spid}/{termid}/pagetpl/{pagetpl_name}/collist/{collist_name}', function ($spid, $termid, $pagetplName, $collistName, Request $request) {

    // 校验SP
    $sp = SP::where(['id' => $spid])->first();
    if (empty($sp)) {
        return response()->json(['status' => '404', 'data' => '无此服务商']);
    }
    // 页面模板名称
    $pagetplName = strtoupper($pagetplName);
    // 页面模板
    $pagetpl = Pagetpl::where(['name' => $pagetplName])->first();
    if (empty($pagetpl)) {
        return response()->json(['status' => '404', 'data' => '无此pageTpl模板']);
    }
    // panelTpl模板paneltplName
    $collist = Collist::where(['name' => $collistName])->first();
    if (empty($collist)) {
        return response()->json(['status' => '404', 'data' => '无此栏目列表']);
    }
    // 获取请求参数
    $whereData = $request->all();
    $pagetplId = $pagetpl->id;
    $collistId = $collist->id;
    // 实例化数据发布接口
    $dataRelease = new CollistRelease();
    // 调用栏目列表发布接口
    $data = $dataRelease->makePagetplCollistData($spid, $termid, $pagetplId, $collistId, $whereData);

    return response()->json(['status' => '200', 'data' => $data]);
});

/**
 * 获取栏目节目数据
 */
Route::get('/ott/{spid}/{termid}/pagetpl/{pagetpl_name}/asset/{asset_id}', function ($spid, $termid, $pagetplName, $assetId, Request $request) {
    // 校验SP
    $sp = SP::where(['id' => $spid])->first();
    if (empty($sp)) {
        return response()->json(['status' => '404', 'data' => '无此服务商']);
    }
    // 页面模板名称
    $pagetplName = strtoupper($pagetplName);
    // 页面模板
    $pagetpl = Pagetpl::where(['name' => $pagetplName])->first();
    if (empty($pagetpl)) {
        return response()->json(['status' => '404', 'data' => '无此pageTpl模板']);
    }
    $paneltplId  = $pagetpl->id;
    $whereData   = $request->all();
    $dataRelease = new MetaDataRelease();
    $data        = $dataRelease->makeAssetData($spid, $termid, $paneltplId, $assetId, $whereData);
    return response()->json(['status' => '200', 'data' => $data]);
});
/**
 * 栏目节目数据发布
 */
Route::get('/ott/{spid}/{termid}/columns/{columns}/column_assets', function ($spid, $termid, $columnId, Request $request, MuticolumnRelease $dataRelease) {
    $sp = SP::where(['id' => $spid])->first();
    if (empty($sp)) {
        return response()->json(['status' => '404', 'data' => '无此服务商']);
    }
    // 获取栏目列表的数据
    $data = $dataRelease->makeMuticolumnAssetDatas($spid, $termid, $columnId, $request->all());

    return response()->json(['status' => '200', 'data' => $data['data'], 'page' => $data['page']]);
});
/**
 * 栏目推荐数据发布
 */
Route::get('/ott/{spid}/{termid}/columns/{columns}/muticolumn_reclist0_datas', function ($spid, $termid, $columnId, Request $request, MuticolumnRelease $dataRelease) {
    $sp = SP::where(['id' => $spid])->first();
    if (empty($sp)) {
        return response()->json(['status' => '404', 'data' => '无此服务商']);
    }
    // 获取栏目列表的数据
    $data = $dataRelease->makeMuticolumnRecommendDatas($spid, $termid, $columnId, $request->all());

    return response()->json(['status' => '200', 'data' => $data['data'], 'page' => $data['page']]);
});
/**
 * 一级栏目发布
 */
Route::get('/ott/{spid}/{termid}/columns', function ($spid, $termid, Request $request, DataRelease $dataRelease) {
    // $query = $request->input('query');
    $sp = SP::where(['id' => $spid])->first();
    if (empty($sp)) {
        return response()->json(['status' => '404', 'data' => '无此服务商']);
    }
    // 获取栏目列表的数据
    $data = $dataRelease->makeColumnDatas($spid, $termid, $request->all());

    return response()->json(['status' => '200', 'data' => $data['data'], 'page' => $data['page']]);
});

/**
 * 二级栏目发布
 */
Route::get('/ott/{spid}/{termid}/subcolumns', function ($spid, $termid, Request $request, DataRelease $dataRelease) {
    // $query = $request->input('query');
    $sp = SP::where(['id' => $spid])->first();
    if (empty($sp)) {
        return response()->json(['status' => '404', 'data' => '无此服务商']);
    }
    // 获取栏目列表的数据
    $data = $dataRelease->makeSubcolumnDatas($spid, $termid, $request->all());

    return response()->json(['status' => '200', 'data' => $data['data'], 'page' => $data['page']]);
});
/**
 * 获取子栏目
 */
Route::get('/ott/{spid}/{termid}/columns/{column_id}/subcolumns', function ($spid, $termid, $columnId, Request $request, DataRelease $dataRelease) {
    // $query       = [];
    // $query['id'] = $columnId;
    $sp = SP::where(['id' => $spid])->first();
    if (empty($sp)) {
        return response()->json(['status' => '404', 'data' => '无此服务商']);
    }
    // 获取栏目列表的数据
    $data = $dataRelease->makeColumnDatas($spid, $termid, $request->all());

    return response()->json(['status' => '200', 'data' => $data['data'], 'page' => $data['page']]);
});
/**
 * 一级栏目推荐接口
 */
Route::get('/ott/{spid}/{termid}/columnrec/{column_id}', function ($spid, $termid, $columnId, Request $request, DataRelease $dataRelease) {

    // 获取栏目列表的数据
    $data = $dataRelease->makeColumnRecommendDatas($spid, $termid, $columnId);
    return response()->json(['status' => '200', 'type' => $data['type'], 'data' => $data['data']]);
});

/**
 * 二级栏目推荐接口
 */
Route::get('/ott/{spid}/{termid}/subcolumnrec/{subcolumn_id}', function ($spid, $termid, $subcolumnId, Request $request, DataRelease $dataRelease) {
    // 获取栏目列表的数据
    $data = $dataRelease->makeSubcolumnRecommendDatas($spid, $termid, $subcolumnId);
    return response()->json(['status' => '200', 'type' => $data['type'], 'data' => $data['data']]);
});

/**
 * 获取页面推荐位
 */
Route::get('/ott/{spid}/{term_id}/arearec/{page_id}/{areaid?}', function ($spid, $termid, $pageId, $areaId = null, Request $request, DataRelease $dataRelease) {
    // 获取页面推荐页
    $data = $dataRelease->makeArearecDatas($spid, $termid, $pageId, $areaId);
    return response()->json(['status' => '200', 'data' => $data]);
});

/**
 * 根据标签过滤相关媒资信息
 */
Route::get('/ott/{spid}/{term_id}/asset/tags/{tagid}', function ($spid, $termid, $tagId, Request $request, DataRelease $dataRelease) {
    // 获取页面推荐页
    // 获取栏目列表的数据
    $data = $dataRelease->makeTagAssetDatas($spid, $termid, $tagId);

    return response()->json(['status' => '200', 'data' => $data['data'], 'page' => $data['page']]);
});

/**
 * 节目详情接口
 */
Route::get('/ott/{spid}/{term_id}/vassset/{vasset_id}', function ($spid, $termid, $vassetId, Request $request, VassetiRelease $dataRelease) {
    $data = $dataRelease->makeVassetiDetailsDatas($spid, $termid, $vassetId);
    return response()->json(['status' => '200', 'data' => $data]);

});

/**
 * 根据总集获取分集
 */
Route::get('/ott/{spid}/{term_id}/episodes/{vasset_id}', function ($spid, $termid, $vassetId, Request $request, VassetiRelease $dataRelease) {
    // $query = $request->input('query');
    $data = $dataRelease->makeVassetiVserialiDatas($spid, $termid, $vassetId, $request->all());
    return response()->json(['status' => '200', 'data' => $data['data'], 'page' => $data['page']]);

});

/**
 * 发布节目清单(全量)
 */
Route::get('/ott/{spid}/{term_id}/vasssets', function ($spid, $termid, Request $request, DataRelease $dataRelease) {
    // $query = $request->input('query');
    // 获取栏目列表的数据
    $data = $dataRelease->makeVassetiDatas($spid, $termid, $request->all());

    return response()->json(['status' => '200', 'data' => $data['data'], 'page' => $data['page']]);

});

/**
 * 获取分集详情
 */
Route::get('/ott/{spid}/{term_id}/vseriali/{vseriali_id}', function ($spid, $termid, $vserialId, Request $request, DataRelease $dataRelease) {
    $data = $dataRelease->makeVserialiDatas($spid, $termid, $vserialId);
    return response()->json(['status' => '200', 'data' => $data]);

});
/**
 * 音频
 */
Route::get('/ott/{spid}/{term_id}/aasssets', function ($spid, $termid, Request $request, DataRelease $dataRelease) {
    $data = [];
    return response()->json(['status' => '200', 'data' => $data]);
    // 要发布的文件目录
    // $dataRelease = new \App\Classes\DataRelease\DataRelease();

    // $dataRelease->releaseColumnDatas();

});

/**
 * 栏目节目列表数据
 */
Route::get('/ott/{spid}/{term_id}/assset/column/{column_id}', function ($spid, $termid, $columnId, Request $request, DataRelease $dataRelease) {
    // $query = $request->input('query');
    $data = $dataRelease->makeAsssetColumnDatas($spid, $termid, $columnId, $request->all());
    return response()->json(['status' => '200', 'data' => $data['data'], 'page' => $data['page']]);
});

/**
 * 获取指定类型指定媒资的分集信息
 */
Route::get('/ott/{spid}/{term_id}/episodes/{asset_type}/{asset_id}', function ($spid, $termid, $assetType, $assetId, Request $request, DataRelease $dataRelease) {
    if (!in_array($assetType, ['vasset', 'aasset', 'iasset'])) {
        return response()->json(['status' => '404', 'data' => '无此资源类型']);
    }
    $data = $dataRelease->makeVserialiDatasByAssetType($spid, $termid, $assetType, $assetId);
    return response()->json(['status' => '200', 'data' => $data]);
});

/**
 * 获取标签列表
 */
Route::get('/ott/{spid}/{termid}/tags', function ($spid, $termid, Request $request, DataRelease $dataRelease) {
    $limit = $request->input('limit') ? intval($request->input('limit')) : 10;

    $data = $dataRelease->makeTagDatas($spid, $termid, $limit);
    return response()->json(['status' => '200', 'data' => $data['data'], 'page' => $data['page']]);
});

/**
 * 获取指定类型指定媒资的分集信息
 */
Route::get('/ott/{spid}/{termid}/meta/{asset_type}/{asset_id}', function ($spid, $termid, $assetType, $assetId, Request $request, DataRelease $dataRelease) {
    $data = [];
    return response()->json(['status' => '200', 'data' => $data]);
});

/**
 * 根据表名和字段名称获取某一列
 */

Route::get('/cms/{model}/{column}', function ($model, $column, Request $request) {
    $page  = $request->input('page');
    $limit = $request->input('limit') ? $request->input('limit') : 10;
    // $tableName  = $request->input('table_name');
    // $tableField = $request->input('field');
    $id = $request->input('id');
    if (empty($model)) {
        return response()->json(['status' => '404', 'data' => '表名不能为空']);
    }
    if (empty($column)) {
        return response()->json(['status' => '404', 'data' => '表字段不能为空']);
    }
    $tablePages = [];
    $publicPage = [];
    if (!Schema::hasTable($model)) {
        return response()->json(['status' => '404', 'data' => '无此表名']);
    }
    if (!Schema::hasColumn($model, $column)) {
        return response()->json(['status' => '404', 'data' => '无此字段']);
    }
    $imgPrefixUrl  = config('custom.base.host.ftp');
    $datas         = [];
    $tableDetail   = DB::table($model)->whereNull('deleted_at')->paginate($limit);
    $datas['data'] = [];
    $data          = [];
    foreach ($tableDetail as $key => $value) {
        $flag                = false;
        $data[$key]['href']  = $imgPrefixUrl . $value->$column;
        $data[$key]['title'] = $value->title;
        if ($value->id == $id) {
            $flag = true;
        }
        $data[$key]['selected'] = $flag;
    }
    $tablePages              = $tableDetail->toArray();
    $publicPage['nowpage']   = $tablePages['current_page'];
    $publicPage['totalpage'] = $tablePages['last_page'];

    $publicPage['prepage']['href']  = $tablePages['prev_page_url'] ? $tablePages['prev_page_url'] . '&limit=' . $limit : $tablePages['prev_page_url'];
    $publicPage['nextpage']['href'] = $tablePages['next_page_url'] ? $tablePages['next_page_url'] . '&limit=' . $limit : $tablePages['next_page_url'];
    if (empty($publicPage)) {
        $publicPage = (object) [];
    }
    $datas['data'] = $data;
    $datas['page'] = $publicPage;
    return response()->json(['status' => '200', 'data' => $datas]);
});

/**
 * 获取range接口
 */
Route::get('/cms/range', function (Request $request) {

    $data = [
        [
            'id'    => 0,
            'title' => '选择',
        ],
        [
            'id'    => 1,
            'title' => 'area',
        ],
        [
            'id'    => 2,
            'title' => 'page',
        ],
        [
            'id'    => 3,
            'title' => 'app',
        ],
        [
            'id'    => 4,
            'title' => 'list',
        ],
    ];
    return response()->json(['status' => '200', 'data' => $data]);
});
/**
 * 根据数据range获取模板接口
 */
Route::get('/cms/range/{range}/tpls', function ($range, Request $request) {
    $datas = [];
    switch ($range) {
        case '1':
            $datas = Paneltpl::get(['title', 'id'])->toArray();
            break;
        case '2':
            $datas = Pagetpl::get(['title', 'id'])->toArray();
            break;
        case '3':
            $datas = Pagetpl::get(['title', 'id'])->toArray();
            break;
        case '4':
            $datas = Pagetpl::get(['title', 'id'])->toArray();
            break;
        default:
            break;
    }
    return response()->json(['status' => 200, 'data' => array_merge([['id' => 0, 'title' => '选择']], $datas)]);
});
/**
 * 获取数据类型
 */
Route::get('/cms/column_types', function (Request $request) {
    $tmpColumnTypes = ColumnType::get(['tags', 'id', 'title', 'pid'])->toArray();
    $tempArr        = [];
    foreach ($tmpColumnTypes as $key => $columnType) {
        $tags = explode(',', $columnType['tags']);
        foreach ($tags as $tag) {
            if (in_array(trim($tag), ['any', 'page_rectpl'])) {
                $tempArr[] = $columnType['id'];
            }
        }
    }
    $columnTypes = ColumnType::whereIn('id', $tempArr)->get(['id', 'pid', 'title'])->toArray();
    return response()->json(['status' => 200, 'data' => array_merge([['id' => 0, 'pid' => 0, 'title' => '选择']], $columnTypes)]);
});
/**
 * 获取数据源
 */
Route::get('/cms/column_types/{column_types}/rectpl/{rectpl_id}/{area}', function ($columnTypeId, $rectplId, $area, Request $request) {
    // 根据推荐位
    $apppageRectplArea = ApppageRectplArea::with(['pagetpl', 'paneltpl'])->where(['apppage_rectpl_id' => $rectplId, 'area' => $area])->first();
    if (empty($apppageRectplArea)) {
        return response()->json(['status' => 404, 'data' => '页面推荐位不合法']);
    }
    $pageId     = $apppageRectplArea->pagetpl_id;
    $paneltplId = $apppageRectplArea->paneltpl_id;
    $area       = $apppageRectplArea->area;
    $whereData  = [];
    // 获取页面推荐区位已有的数据
    $pageRectpldataIds = ApppageRectplData::where(['apppage_rectpl_area_id' => $apppageRectplArea->id, 'pagetpl_id' => $pageId, 'paneltpl_id' => $paneltplId, 'area' => $area, 'data_id' => $columnTypeId])->pluck('resource_data_id')->toArray();
    $relation          = [];
    $columnType        = ColumnType::where(['id' => $columnTypeId])->first();
    // 栏目类型为空的话
    if (empty($columnType)) {
        return response()->json($data);
    }
    if ($columnType) {
        switch ($columnType->name) {
            case 'collist':
                $model = new Collist();
                break;
            case 'column':
                $model = new Muticolumn();
                break;
            case 'vodpkg':
                $model    = new Vasseti();
                $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                break;
            case 'livepkg':
                $model    = new Vasseti();
                $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                break;
            case 'vasset':
                $model    = new Vasseti();
                $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                break;
            case 'panellist':
                $model = new ApppageRectpl();
                break;
            case 'reclist0':
                $model = new Reclist0();
                break;
            case 'assetpkg':
                $model    = new Vasseti();
                $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                break;
            case 'aasset':
                $model    = new Vasseti();
                $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                break;
            case 'iasset':
                $model    = new Vasseti();
                $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                break;
            case 'SPDJ':
                $model     = new Vasseti();
                $whereData = ['serials' => 1];
                $relation  = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                break;
            case 'SPFJ':
                $model    = new Vasseti();
                $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                break;
            default:
                break;
        }
    }
    // 获取类名称
    $model        = (new \ReflectionClass($model))->getName();
    $data         = [];
    $data['draw'] = $request->get('draw');
    // $start        = $request->get('start') ?: 0;
    // $length       = $request->get('length') ?: 10;
    $order   = $request->get('order');
    $columns = $request->get('columns');
    $search  = $request->get('search');
    if ($order) {
        $orderColumData = $columns[$order[0]['column']]['data'];
    }

    // 排序字段
    $ord = '';
    if (!empty($orderColumData)) {
        $ord = $orderColumData . ' ' . $order[0]['dir'];
    } else {
        $ord = 'id asc';
    }
    // ->skip($start)
    // ->take($length)
    $recordsTotalQuery    = $model::where($whereData)->whereNotIn('id', $pageRectpldataIds);
    $recordsFilteredQuery = $model::where($whereData)->whereNotIn('id', $pageRectpldataIds);
    $dataQuery            = $model::with($relation)
        ->whereNotIn('id', $pageRectpldataIds)
        ->where($whereData)
        ->orderByRaw($ord);
    // 如果是视频分集的话, 新增条件集数大于1的
    if ($columnType->name == 'SPFJ') {
        $recordsTotalQuery->where('serials', '>', 1);
        $recordsFilteredQuery->where('serials', '>', 1);
        $dataQuery->where('serials', '>', 1);
    }
    $data['recordsTotal']    = $recordsTotalQuery->count();
    $data['recordsFiltered'] = $recordsFilteredQuery->count();
    $data['data']            = $dataQuery->get();
    return response()->json($data);

});

/**
 * 保存模板数据
 */
Route::post('/cms/rectpl/{rectpl_id}/templates/{area}', function ($rectplId, $area, Request $request) {
    $apppageRectpl = ApppageRectpl::with(['apppageRectplArea'])->where(['id' => $rectplId])->first();
    if (empty($apppageRectpl)) {
        return response()->json(['status' => '404', 'data' => '推荐位不合法']);
    }
    $datas = $request->input('data');

    // 根据区位获取
    $apppageRectplArea = ApppageRectplArea::with(['pagetpl', 'paneltpl'])->where(['apppage_rectpl_id' => $rectplId, 'area' => $area])->first();
    if (empty($apppageRectplArea)) {
        return response()->json(['status' => '404', 'data' => '推荐区位不合法']);
    }

    DB::beginTransaction();
    try {
        $apppageRectplAreaDatas = [];
        foreach ($datas as $datakey => $dataValue) {
            // 根据推荐位
            $img                                                        = $dataValue['img'];
            $insertMode                                                 = 1;
            $apppageRectplAreaDatas[$datakey]['subtitle']               = $dataValue['title'];
            $apppageRectplAreaDatas[$datakey]['apppage_rectpl_area_id'] = $apppageRectplArea->id;
            $apppageRectplAreaDatas[$datakey]['paneltpl_id']            = $apppageRectplArea->paneltpl_id;
            $apppageRectplAreaDatas[$datakey]['pagetpl_id']             = $apppageRectplArea->pagetpl_id;
            $apppageRectplAreaDatas[$datakey]['area']                   = $apppageRectplArea->area;
            $apppageRectplAreaDatas[$datakey]['position']               = $dataValue['area'];
            if (!empty($img)) {
                $image = explode('/', $img);
                $image = end($image);
                // 上传图片
                $uploadConfig = config('custom.base.upload.apppage_rectpl_data');
                $dir          = $uploadConfig['dir'];
                $img          = 'upload/' . $dir . '/' . $image;
            }
            $apppageRectplAreaDatas[$datakey]['img']   = $img;
            $apppageRectplAreaDatas[$datakey]['order'] = (isset($dataValue['order']) && !empty($dataValue['order'])) ? $dataValue['order'] : 0;
            // 插入模式
            $apppageRectplAreaDatas[$datakey]['range']            = $dataValue['range'];
            $apppageRectplAreaDatas[$datakey]['tpl_id']           = $dataValue['tpl_id'];
            $apppageRectplAreaDatas[$datakey]['data_id']          = $dataValue['data_type'];
            $apppageRectplAreaDatas[$datakey]['resource_data_id'] = $dataValue['data_id'];
            // insert_mode , 根据数据类型判断是否为栏目列表或者是推荐数据
            $columnTypeName = ColumnType::where(['id' => $dataValue['data_type']])->value('name');
            if (in_array($columnTypeName, ['collist', 'reclist0'])) {
                $insertMode = 2;
            }
            $apppageRectplAreaDatas[$datakey]['insert_mode'] = $insertMode;

            // 根据栏目类型获取栏目名称
            $columnTypeName = ColumnType::where(['id' => $dataValue['data_type']])->value('name');
            switch ($columnTypeName) {
                case 'collist':
                    $title = Collist::where(['id' => $dataValue['data_id']])->value('title');
                    break;
                case 'column':
                    $title = Muticolumn::where(['id' => $dataValue['data_id']])->value('title');
                    break;
                case 'vodpkg':
                    $title = Vasseti::where(['id' => $dataValue['data_id']])->value('title');
                    break;
                case 'livepkg':
                    $title = Vasseti::where(['id' => $dataValue['data_id']])->value('title');
                    break;
                case 'panellist':
                    $title = ApppageRectpl::where(['id' => $dataValue['data_id']])->value('title');
                    break;
                case 'reclist0':
                    $title = Reclist0::where(['id' => $dataValue['data_id']])->value('title');
                    break;
                case 'vasset':
                    $title = Vasseti::where(['id' => $dataValue['data_id']])->value('title');
                    break;
                case 'aasset':
                    $title = Vasseti::where(['id' => $dataValue['data_id']])->value('title');
                    break;
                case 'iasset':
                    $title = Vasseti::where(['id' => $dataValue['data_id']])->value('title');
                    break;
                case 'assetpkg':
                    $title = Vasseti::where(['id' => $dataValue['data_id']])->value('title');
                    break;
                case 'SPDJ':
                    $title = Vasseti::where(['id' => $dataValue['data_id']])->value('title');
                    break;
                case 'SPFJ':
                    $title = Vasseti::where(['id' => $dataValue['data_id']])->value('title');
                    break;
                default:
                    $title = '';
                    break;
            }
            $apppageRectplAreaDatas[$datakey]['title']       = $title;
            $apppageRectplAreaDatas[$datakey]['description'] = $dataValue['message'];
        }
        // dd($apppageRectplAreaDatas);
        // dd($apppageRectplArea->id);
        // 先删除此推荐位的所有数据
        DB::table('apppage_rectpl_datas')->where('apppage_rectpl_area_id', $apppageRectplArea->id)->delete();
        DB::table('apppage_rectpl_datas')->insert($apppageRectplAreaDatas);
        DB::commit();
        return response()->json(['status' => '200', 'data' => '数据保存成功']);

    } catch (Exception $e) {
        DB::rollBack();
        dd($e->getMessage(), $e->getLine());
    }
});

/**
 * 图片上传
 */
Route::post('/cms/images', function (Request $request) {
    $image = $request->file('img');
    if ($image) {
        // 如果图片不合法, 则跳过
        if (!$image->isValid()) {
            return response()->json(['status' => 'error', 'content' => '上传图片不合法!']);
        }
        // 允许上传的图片格式, 如果不满足, 则跳过
        $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
        if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
            return response()->json(['status' => 'error', 'content' => '上传图片格式只能是png, jpg, gif, jpeg!']);
        }
        // 临时文件的绝对路径
        $realPath = $image->getRealPath();
        // 获得图片的扩展名
        $extension = $image->getClientOriginalExtension();
        // 重新命名上传文件名字
        $newImageName = md5(time()) . random_int(100, 999) . "." . $extension;
        // 上传图片
        $uploadConfig = config('custom.base.upload.apppage_rectpl_data');
        $driver       = $uploadConfig['driver'];
        $dir          = $uploadConfig['dir'];
        $rootDir      = config('filesystems.disks.' . $driver . '.upload');
        // 图片的完整路径
        $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;
        $bool     = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
        if (!$bool) {
            return response()->json(['status' => 'error', 'content' => '上传图片失败!']);
        } else {
            return response()->json(['status' => 'success', 'content' => $fullPath]);
        }
    } else {
        return response()->json(['status' => 'error', 'content' => '没有上传图片或上传图片不存在!']);
    }
});

/**
 * 区位数据回填
 */
Route::get('/cms/apppage_rectpls/{rectpl_id}/area/{area}', function ($rectplId, $area, Request $request) {
    // 获取请求参数
    $whereData = $request->all();
    // 根据栏目模板ID,页面Id获取推荐位
    $apppageRectpl = ApppageRectpl::where(['id' => $rectplId])->first();
    if (empty($apppageRectpl)) {
        return response()->json(['status' => '404', 'data' => '无此推荐位']);
    }
    // 实例化数据发布接口
    $dataRelease = new ApppageRectplRelease();
    // 调用栏目列表发布接口
    $data = $dataRelease->makePageRectplAreaDatas($rectplId, $area, $whereData);

    return response()->json(['status' => '200', 'type' => $data['type'], 'data' => $data['data']]);
});

/**
 * 根据页面样式获取页面素材
 */
Route::get('/ott/{spid}/{term_id}/page_styles/{page_style}', function ($spid, $termid, $pageStyleName, Request $request) {
    // 获取请求参数
    $whereData = $request->all();
    // 根据页面样式名称获取页面样式详情
    $pageStyle = PageStyle::with(['pageIcons'])->where(['name' => strtoupper($pageStyleName)])->first();
    if (empty($pageStyle)) {
        return response()->json(['status' => '404', 'data' => '页面样式不合法']);
    }

    $data             = [];
    $data['id']       = $pageStyle->id;
    $data['name']     = $pageStyle->name;
    $data['title']    = $pageStyle->title;
    $data['subtitle'] = $pageStyle->subtitle;
    $data['ui']       = config('custom.base.api.host') . $pageStyle->ui;
    $data['data']     = $pageStyle->pageIcons;

    return response()->json(['status' => '200', 'data' => $data]);
});

/**
 * 根据表名获取数据
 */
Route::get('/tables/{table_name}', function ($tableName, Request $request) {
    if (!Schema::hasTable($tableName)) {
        return response()->json(['status' => '404', 'data' => '非法操作']);
    }
    $listorder = $request->input('listorder') ? $request->input('listorder') : 'asc';
    $column    = 'listorder';
    $query     = DB::table($tableName)->whereNull('deleted_at');
    if (Schema::hasColumn($tableName, $column)) {
        $query->orderBy($column, $listorder);
    }
    $result = $query->get();
    return $result;
});

/**
 * 拖拽排序
 */
Route::post('/tables/listorder', function (Request $request) {
    $tableName = $request->input('table');
    if (!Schema::hasTable($tableName)) {
        return response()->json(['status' => '404', 'data' => '无此表名']);
    }
    $column = 'listorder';
    // 检查此表是否有listorder字段
    if (!Schema::hasColumn($tableName, $column)) {
        return response()->json(['status' => '404', 'data' => '该表无listorder字段']);
    }
    // 获取拖拽行的ID
    $rowId       = $request->input('row_id');
    $insertRowId = $request->input('insert_row_id');
    $rowTable    = DB::table($tableName)->whereNull('deleted_at')
        ->where(['id' => $rowId])->first();
    $insertRowTable = DB::table($tableName)->whereNull('deleted_at')
        ->where(['id' => $insertRowId])->first();
    if (empty($rowTable) || empty($insertRowTable)) {
        return response()->json(['status' => '404', 'data' => '非法查询']);
    }
    $rowOrder       = $rowTable->listorder;
    $insertRowOrder = $insertRowTable->listorder;
    DB::beginTransaction();
    try {
        // 判断row和insert那个大
        if (intval($rowOrder) < intval($insertRowOrder)) {
            $tables = DB::table($tableName)->where('listorder', '>', $rowOrder)
                ->where('listorder', '<=', $insertRowOrder)
                ->whereNull('deleted_at')
                ->get();
            $updateResult = DB::table($tableName)->where(['id' => $rowId])->update(['listorder' => $insertRowOrder]);
            // 获DB::table($tableName)->where(['id' => $rowId])->first();取insertRowId的排序值
            foreach ($tables as $key => $value) {
                DB::table($tableName)->where(['id' => $value->id])->update(['listorder' => ($value->listorder - 1)]);
            }
        } elseif ((intval($rowOrder) > intval($insertRowOrder))) {
            $tables = DB::table($tableName)->where('listorder', '>=', $insertRowOrder)
                ->where('listorder', '<', $rowOrder)
                ->whereNull('deleted_at')
                ->get();
            // dd($tables->toArray());
            $updateResult = DB::table($tableName)->where(['id' => $rowId])->whereNull('deleted_at')->update(['listorder' => $insertRowOrder]);
            // 获DB::table($tableName)->where(['id' => $rowId])->first();取insertRowId的排序值
            foreach ($tables as $key => $value) {
                DB::table($tableName)->where(['id' => $value->id])->whereNull('deleted_at')->update(['listorder' => ($value->listorder + 1)]);
            }
        }
        DB::commit();
        return response()->json(['status' => '200', 'data' => '排序成功']);
    } catch (Exception $e) {
        DB::rollback();
        dd($e->getMessage(), $e->getCode());
    }
});

/**
 * 更新表字段的排序
 */
Route::post('/tables/listorder/update', function (Request $request) {
    $tableName = $request->input('table');
    if (!Schema::hasTable($tableName)) {
        return response()->json(['status' => '404', 'data' => '非法表名']);
    }
    DB::beginTransaction();
    try {
        $tableIds = DB::table($tableName)->whereNull('deleted_at')->pluck('id');
        if (!empty($tableIds->first())) {
            foreach ($tableIds as $key => $value) {
                DB::table($tableName)->where(['id' => $value])->whereNull('deleted_at')->update(['listorder' => $key + 1]);
            }
            DB::commit();
            return response()->json(['status' => '200', 'data' => '更新成功']);
        } else {
            return response()->json(['status' => '404', 'data' => '表中无数据']);
        }
    } catch (Exception $e) {
        DB::rollBack();
        dd($e->getMessage(), dd($e->getCode()));
    }
});

/**
 * 加载json schema
 */
Route::get('/json/schema/tables/{table_name}/field/{field_name}', function ($tableName, $fieldName, Request $request) {
    // dd($tableName);
    $table = Table::where(['name' => $tableName])->first();
    if (empty($table)) {
        return response()->json(['status' => '404', 'data' => '无此表']);
    }
    $tableField = TableField::where(['name' => $fieldName, 'table_id' => $table->id])->first();
    if (empty($tableField)) {
        return response()->json(['status' => '404', 'data' => '无此字段']);
    }
    $data               = [];
    $data['table_name'] = $tableName;
    $data['field_name'] = $fieldName;
    $schema             = JsonField::where(['table_id' => $table->id, 'table_field_id' => $tableField->id])->value('schema');
    $data['schema']     = json_decode($schema);
    $data['data']       = json_decode($tableField->attr);
    return response()->json(['status' => '200', 'data' => $data]);
});

/**
 * 用户调用接口回填数据
 */
Route::post('/json/schema/tables/{table_name}/field/{field_name}', function ($tableName, $fieldName, Request $request) {
    $data = $request->input('data');
    if (empty($data)) {
        return response()->json(['status' => '404', 'data' => '数据不能为空']);
    }
    $table = Table::where(['name' => $tableName])->first();
    if (empty($table)) {
        return response()->json(['status' => '404', 'data' => '无此表']);
    }
    $tableField = TableField::where(['name' => $fieldName, 'table_id' => $table->id])->first();
    if (empty($tableField)) {
        return response()->json(['status' => '404', 'data' => '无此字段']);
    }

    $result = TableField::where(['id' => $tableField->id])->update(['attr' => $data]);
    if ($result) {
        return response()->json(['status' => '200', 'data' => '保存成功']);
    } else {
        return response()->json(['status' => '404', 'data' => '保存失败']);
    }
});

/**
 * 获取posters数据表数据
 */
Route::get('/posters', function (Request $request) {
    try {
        $data    = [];
        $datas   = [];
        $posters = Poster::with(['posterHrefs'])->get();
        if (!empty($posters->first())) {
            foreach ($posters as $key => $value) {
                $data[$key]['posterId']   = $value->posterId;
                $data[$key]['title']      = $value->title;
                $data[$key]['subtitle']   = $value->subtitle;
                $data[$key]['short_desc'] = $value->short_desc;
                $data[$key]['details']    = $value->detail;
                $data[$key]['thumbnail']  = $value->thumbnail;
                $data[$key]['tags'][]     = $value->tags;
                $imgs                     = [];
                if (count($value->posterHrefs)) {

                    foreach ($value->posterHrefs as $posterKey => $posterValue) {
                        $imgs[$posterKey]['imgtpl'] = $posterValue->imgtpl_id;
                        $imgs[$posterKey]['href']   = $posterValue->path;
                    }
                }
                $data[$key]['imgs'] = $imgs;
            }
            $datas['metaId'] = null;
            $datas['datas']  = $data;
        }
        return response()->json(['status' => 200, 'data' => $datas]);
    } catch (Exception $e) {
        return response()->json(['status' => '404', 'data' => [$e->getMessage(), $e->getLine()]]);
    }

});

/**
 * 提交poster表
 */
Route::post('/posters', function (Request $request) {
    $metaId = $request->input('metaId');
    $datas  = $request->input('datas');
    if (empty($datas)) {
        return response()->json(['status' => '404', 'data' => '数据不能为空']);
    }
    DB::beginTransaction();
    try {
        foreach ($datas as $key => $value) {
            $data               = [];
            $data['posterId']   = $value['posterId'];
            $data['title']      = $value['title'];
            $data['subtitle']   = $value['subtitle'];
            $data['short_desc'] = $value['short_desc'];
            $data['detail']     = $value['details'];
            $data['thumbnail']  = $value['thumbnail'];
            $data['tags']       = $value['tags'];
            $data['created_at'] = date('Y-m-d H:i:s');
            // $data[$key]['imgs'] = $value['imgs'];
            $posterId   = DB::table('posters')->insertGetId($data);
            $posterHref = [];
            foreach ($value['imgs'] as $posterHrefKey => $posterHrefValue) {
                $posterHref[$posterHrefKey]['posterId']  = $value['posterId'];
                $posterHref[$posterHrefKey]['imgtpl_id'] = $posterHrefValue['imgtpl'];
                $posterHref[$posterHrefKey]['path']      = $posterHrefValue['href'];
                $posterHref[$posterHrefKey]['storage']   = $posterHrefValue['href'];
            }
            if (!empty($posterHref)) {
                DB::table('poster_hrefs')->insert($posterHref);
            }
        }
        DB::commit();
        return response()->json(['status' => '200', 'data' => '数据保存成功']);
    } catch (Exception $e) {
        DB::rollBack();
        return response()->json(['status' => '404', 'data' => [$e->getMessage(), $e->getLine()]]);
    }
});

/**
 * 获取单个poster信息
 */
Route::get('/posters/{posters}', function ($id, Request $request) {

    try {
        $data    = [];
        $datas   = [];
        $poster = Poster::with(['posterHrefs'])->where(['posterId' => $id])->first();
        if (!empty($poster)) {
            $data['posterId']   = $poster->posterId;
            $data['title']      = $poster->title;
            $data['subtitle']   = $poster->subtitle;
            $data['short_desc'] = $poster->short_desc;
            $data['details']    = $poster->detail;
            $data['thumbnail']  = $poster->thumbnail;
            $data['tags'][]     = $poster->tags;
            $imgs               = [];
            if (count($poster->posterHrefs)) {
                foreach ($poster->posterHrefs as $posterKey => $posterValue) {
                    $imgs[$posterKey]['imgtpl'] = $posterValue->imgtpl_id;
                    $imgs[$posterKey]['href']   = $posterValue->path;
                }
            }
            $data['imgs']    = $imgs;
            $datas['metaId'] = null;
            $datas['datas']  = $data;
        }
        return response()->json(['status' => 200, 'data' => $datas]);
    } catch (Exception $e) {
        return response()->json(['status' => '404', 'data' => [$e->getMessage(), $e->getLine()]]);
    }
});
